<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="机构名称" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入机构名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manage:messageChannel:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:messageChannel:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:messageChannel:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['manage:messageChannel:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="channelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="机构名称" align="center" prop="tenantName"/>
      <el-table-column label="已配置渠道" align="center" prop="messageChannelName"/>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.createTime  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleAddOrdinaryMessage(scope.row)"
          >创建消息推送
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:messageChannel:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:messageChannel:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改机构消息渠道信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属机构" prop="tenantId">
          <el-select
            v-model="form.tenantId"
            filterable
            remote
            placeholder="输入机构名称搜索"
            :remote-method="getTenantList"
            :loading="getTenantListLoading"
            :disabled="!!form.messageChannelId"
          >
            <el-option
              v-for="item in tenantList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- ：0.开启；1.关闭-->
        <el-form-item label="企业微信" prop="wechatState">
          <el-switch
            v-model="form.wechatState"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="0"
            inactive-value="1"
            @change="channelListening('1')"
          >
          </el-switch>
        </el-form-item>


        <el-form-item label="Corpid" prop="wechatCorpid">
          <el-input v-model="form.wechatCorpid" placeholder="请输入企业微信Corpid"
                    :disabled="!wechatState"/>
        </el-form-item>
        <el-form-item label="AgentId" prop="wechatAgentId">
          <el-input v-model="form.wechatAgentId" placeholder="请输入企业微信AgentId"
                    :disabled="!wechatState"/>
        </el-form-item>
        <el-form-item label="Secret" prop="wechatSecret">
          <el-input v-model="form.wechatSecret" placeholder="请输入企业微信Secret"
                    :disabled="!wechatState"/>
        </el-form-item>

        <!-- ：0.开启；1.关闭-->
        <el-form-item label="钉钉" prop="dingState">
          <el-switch
            v-model="form.dingState"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="0"
            inactive-value="1"
            @change="channelListening('2')"
          >
          </el-switch>
        </el-form-item>

        <el-form-item label="AgentId" prop="dingAgentId">
          <el-input v-model="form.dingAgentId" placeholder="请输入钉钉AgentId" :disabled="!dingState"/>
        </el-form-item>
        <el-form-item label="AppKey" prop="dingAppKey">
          <el-input v-model="form.dingAppKey" placeholder="请输入钉钉AppKey" :disabled="!dingState"/>
        </el-form-item>
        <el-form-item label="AppSecret" prop="dingAppSecret">
          <el-input v-model="form.dingAppSecret" placeholder="请输入钉钉AppSecret" :disabled="!dingState"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改普通消息推送对话框 -->
    <add :show.sync="addOpen" :data="form" :title="title" :isAssignTenant="true" @success="getList"/>
  </div>
</template>

<script>
import {
  addChannel,
  delChannel,
  getChannel,
  listChannel,
  pageDepartment,
  updateChannel,
  verify
} from "@/api/messageCenter/channel";
import Add from "@/views/messageCenter/ordinaryMessage/components/add.vue";

export default {
  name: "Channel",
  components: {Add},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 机构列表
      tenantList: [],
      // 机构列表加载状态
      getTenantListLoading: false,
      // 总条数
      total: 0,
      // 机构消息渠道信息表格数据
      channelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      addOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantId: null,
        tenantName: null,
        messageChannelName: null,
        wechatState: null,
        wechatCorpid: null,
        wechatAgentId: null,
        wechatSecret: null,
        dingState: null,
        dingAgentId: null,
        dingAppKey: null,
        dingAppSecret: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tenantId: [
          {required: true, message: "请选择所属机构", trigger: "blur"}
        ]
      }
    };
  },
  computed: {
    wechatState() {
      return this.form.wechatState === '0'   // 0.开启；1.关闭
    },
    dingState() {
      return this.form.dingState === '0'   // 0.开启；1.关闭
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询机构消息渠道信息列表 */
    getList() {
      this.loading = true;
      listChannel(this.queryParams).then(response => {
        this.channelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取机构列表
    getTenantList(data) {
      console.log('getTenantList:data', data)
      this.getTenantListLoading = true;
      let params = {
        pageNum: 1,
        pageSize: 10,
        tenantName: data
      }
      pageDepartment(params).then(response => {
        console.log('response', response)
        this.tenantList = response.rows.map(item => {
          return {
            value: item.tenantId,
            label: item.tenantName
          }
        })
        this.getTenantListLoading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        messageChannelId: null,
        tenantId: null,
        tenantName: null,
        messageChannelName: null,
        wechatState: null,
        wechatCorpid: null,
        wechatAgentId: null,
        wechatSecret: null,
        dingState: null,
        dingAgentId: null,
        dingAppKey: null,
        dingAppSecret: null,
        createBy: null,
        updateBy: null,
        createTime: null,
        updateTime: null,
        remark: null,
        delFlag: null
      };
      this.resetForm("form");
      this.tenantList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.messageChannelId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加机构消息渠道信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const messageChannelId = row.messageChannelId || this.ids
      getChannel(messageChannelId).then(response => {
        this.getTenantList(response.data.tenantName)
        this.form = response.data;
        this.open = true;
        this.title = "修改机构消息渠道信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.messageChannelId != null) {
            updateChannel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addChannel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const messageChannelIds = row.messageChannelId || this.ids;
      this.$modal.confirm('是否确认删除此数据项？').then(function () {
        return delChannel(messageChannelIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/channel/export', {
        ...this.queryParams
      }, `channel_${new Date().getTime()}.xlsx`)
    },
    // 1.企业微信，2.钉钉，3.商家小程序，4.租客小程序
    channelListening(channelType) {
      let channelState = false;
      if (channelType === '1') {
        channelState = this.form.wechatState === '1';
      } else if (channelType === '2') {
        channelState = this.form.dingState === '1';
      }
      let query = {
        tenantId: this.form.tenantId,
        pushChannel: channelType,
      }
      if (channelState) {
        verify(query).then(response => {
        }).catch(error => {
          if (channelType === '1') {
            this.form.wechatState = '0';
          } else if (channelType === '2') {
            this.form.dingState = '0';
          }
        })

      }
    },
    handleAddOrdinaryMessage(row) {
      this.form = {
        tenantId: row.tenantId,
        tenantName: row.tenantName,
      }
      this.addOpen = true;
      this.title = "添加普通消息推送";
    }
  }
};
</script>
